package com.solome.oc;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Application.ApplicationType;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Dialog;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.List;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.SelectBox;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.List.ListStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.SelectBox.SelectBoxStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.scenes.scene2d.ui.VerticalGroup;
import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup;
import com.badlogic.gdx.scenes.scene2d.ui.Window.WindowStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.SnapshotArray;
import com.solome.base.AbstractScreen;
import com.solome.base.GameStatus;
import com.solome.base.Logger;
import com.solome.net.ByteArray;
import com.solome.net.HTTP;
import com.solome.net.NetCallback;
import com.solome.util.FontFactory;

import static com.badlogic.gdx.scenes.scene2d.actions.Actions.alpha;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.parallel;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.rotateBy;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.scaleTo;
import static com.badlogic.gdx.scenes.scene2d.actions.Actions.sequence;

public class CodeUi extends AbstractScreen implements NetCallback {

	static final String UTF_8_CN = ":物品名称星级编号收拾";

	WidgetGroup controller;
	WidgetGroup menuController; // 定义一个菜单控制器

	WidgetGroup infoController; // 内容定义一个菜单控制器
	boolean menuAction = false;

	WidgetGroup barController; // 定义一个菜单bar控制器

	BitmapFont bitmapFont = FontFactory.getInstance().init(UTF_8_CN, 15);
	// skin
	final Skin skin = new Skin(Gdx.files.internal("data/uiskin.json"));

	public CodeUi(Game game) {
		super(game);
		// TODO Auto-generated constructor stub

	}

	@Override
	public void pause() {
		// TODO Auto-generated method stub
		Logger.error(this,
				Thread.currentThread().getStackTrace()[2].getMethodName());
		// this.paused = true;

		// PersonFactory<Person> personFactory = Person::new;
		// Person person = personFactory.create("Peter", "Parker");

		// LocalDate today = LocalDate.now();
		// LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
		// LocalDate yesterday = tomorrow.minusDays(2);
		//
		// LocalDate independenceDay = LocalDate.of(2015, Month.JULY, 4);
		// DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
		// System.out.println(dayOfWeek); // FRIDAY

	}

	@Override
	public void resume() {
		// TODO Auto-generated method stub
		Logger.error(this,
				Thread.currentThread().getStackTrace()[2].getMethodName());
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		// 总控制层
		controller = new WidgetGroup();
		controller.setDebug(true);
		controller.setBounds(0, 0, this.getWidth(), this.getHeight());
		this.add(controller);

		{// 菜单层
			initMenuController();
		}

		{// 信息控制层
			initCodeInfo();
		}
		// infoController.addListener(new InputListener() {
		// public boolean touchDown(InputEvent event, float x, float y,
		// int pointer, int button) {
		// // These come from Actor#parentToLocalCoordinates.
		// menuControllerAction();
		// return true;
		// }
		// });

		this.setInputAdapter();
		this.setDebugGameInfo(true);
	}

	public void initCodeInfo() {

		infoController = new WidgetGroup();
		infoController.setName("info");
		infoController.setBounds(150, 0, this.getWidth() - 150,
				this.getHeight() - 1);

		// 说明
		final LabelStyle labelStyle = new LabelStyle();
		labelStyle.font = bitmapFont;
		Label label = new Label("说明:\n   这是一个激活码生成页面.相关母料请前往xls文件中获取",
				labelStyle);
		label.setColor(Color.RED);
		label.setPosition(0, infoController.getHeight() - label.getHeight()
				- 15);
		infoController.addActor(label);

		final WidgetGroup get = new WidgetGroup();
		get.setDebug(true);
		get.setColor(Color.GREEN);
		get.setBounds(infoController.getWidth() - 250, 0, 250,
				infoController.getHeight() - 100);
		get.setName("get");
		infoController.addActor(get);
		controller.addActor(infoController);

		float get_y = get.getHeight() - label.getHeight();

		label = new Label("说明:\n选项获取您要生成的激活码数据.", labelStyle);
		label.setColor(Color.BLACK);
		label.setPosition(0, get_y);
		get.addActor(label);

		get_y = get.getHeight() - 65;
		TextButtonStyle style = new TextButtonStyle(
				skin.get(TextButtonStyle.class));
		style.font = bitmapFont;
		Button iconButton = new TextButton("获取数据", style);
		iconButton.setBounds(15, get_y, 80, 30);
		get.addActor(iconButton);

		SelectBoxStyle boxStyle = skin.get(SelectBoxStyle.class);
		boxStyle.font = bitmapFont;
		boxStyle.listStyle.font = bitmapFont;
		final SelectBox<String> selectBox = new SelectBox<String>(boxStyle);
		selectBox.setItems("卡牌", "物品");
		selectBox.setBounds(15 + iconButton.getWidth() + 10, get_y, 60, 30);
		get.addActor(selectBox);

		final SelectBox<String> starBox = new SelectBox<String>(boxStyle);
		starBox.setItems("星级", "5", "4", "3", "2", "1");
		starBox.setSelected("5");
		starBox.setBounds(selectBox.getX() + selectBox.getWidth() + 10, get_y,
				60, 30);
		get.addActor(starBox);

		final ListStyle listStyle = skin.get(ListStyle.class);
		listStyle.font = bitmapFont;
		final CodeUi self = this;
		iconButton.addListener(new ChangeListener() {
			public void changed(ChangeEvent event, Actor actor) {
				HTTP.send(
						new ByteArray().Allocate(10000)
								.PutUTF(selectBox.getSelected())
								.PutUTF(starBox.getSelected()), self);
			}
		});
		TextFieldStyle fieldStyle = skin.get(TextFieldStyle.class);
		fieldStyle.font = bitmapFont;
		fieldStyle.messageFont = bitmapFont;
		//
		get_y -= iconButton.getHeight() - 5;
		// list.getSelection().setToggle(true);
		ScrollPane scrollPane = new ScrollPane(null, skin);
		scrollPane.setBounds(2, 0, get.getWidth(), get_y);
		scrollPane.setName("dataScroll");
		scrollPane.setScrollingDisabled(true, false);
		get.addActor(scrollPane);

		label = new Label("选择您要编辑的内容.", labelStyle);
		label.setColor(Color.GREEN);
		label.setPosition(0, infoController.getHeight() - 180);
		infoController.addActor(label);
		final SelectBox<String> infoBox = new SelectBox<String>(boxStyle);
		infoBox.setItems("卡牌", "物品", "游戏币", "代币", "声望");
		infoBox.setSelected("卡牌");
		infoBox.setBounds(0, label.getY() - label.getHeight() - 22, 90, 30);
		infoController.addActor(infoBox);

		iconButton = new TextButton("确定添加", style);
		iconButton.setBounds(10 + infoBox.getWidth(),
				label.getY() - label.getHeight() - 22, 70, 15);
		infoController.addActor(iconButton);
		iconButton.addListener(new ChangeListener() {
			public void changed(ChangeEvent event, Actor actor) {
				ScrollPane scrollPane = infoController.findActor("edit");
				WidgetGroup group = (WidgetGroup) scrollPane.getWidget();
				final String selected = infoBox.getSelected();
				switch (selected) {
				case "卡牌":
					group.addActor(getTable("卡牌编辑:", 0, 0, "card",
							"请输入编辑的卡牌ID!", "卡牌数量!"));
					break;
				case "物品":
					group.addActor(getTable("物品编辑:", 0, 0, "item",
							"请输入编辑的物品ID!", "物品数量!"));
					break;
				case "游戏币":
					group.addActor(getTable("游戏币编辑:", 0, 0, "money", null,
							"游戏币数量!"));
					break;
				case "代币":
					group.addActor(getTable("代币编辑:", 0, 0, "stone", null,
							"代币数量!"));
					break;
				case "声望":
					group.addActor(getTable("声望编辑:", 0, 0, "repute", null,
							"声望数量!"));
					break;
				}
			}
		});

		Table table = new Table(skin);
		table.setName("over");
		table.setPosition(0, infoController.getHeight() - 150);
		infoController.addActor(table);
		iconButton = new TextButton("确认编辑", style);
		table.add(iconButton);
		table.pack();
		TextField textfield = new TextField("", skin);
		textfield.setMessageText("请输入批次ID");
		textfield.setName("id");
		table.add(textfield);
		table.pack();
		textfield = new TextField("", skin);
		textfield.setMessageText("失效时间(单位:天)");
		textfield.setName("day");
		table.add(textfield);
		table.pack();
		textfield = new TextField("", skin);
		textfield.setMessageText("生成的数量");
		textfield.setName("num");
		table.add(textfield);

		WidgetGroup group = new VerticalGroup();
		scrollPane = new ScrollPane(group, skin);
		scrollPane.setBounds(5, 0,
				infoController.getWidth() - 10 - get.getWidth(),
				infoController.getHeight() - 250);
		scrollPane.setName("edit");
		group.addActor(getTable("卡牌编辑:", 0, 0, "card", "请输入编辑的卡牌ID!", "卡牌数量!"));
		infoController.addActor(scrollPane);

		// infoController.addActor(getTable("物品编辑:", infoController.getX(),
		// infoController.getHeight() - 250, "item", "请输入编辑的物品ID!",
		// "物品数量!"));
		//
		// infoController.addActor(getTable("游戏币编辑:", infoController.getX(),
		// infoController.getHeight() - 300, "money", null, "游戏币数量!"));
		// //
		// infoController.addActor(getTable("代币编辑:", infoController.getX(),
		// infoController.getHeight() - 350, "stone", null, "代币数量!"));
		//
		// infoController.addActor(getTable("声望编辑:", infoController.getX(),
		// infoController.getHeight() - 400, "repute", null, "声望数量!"));

		iconButton.addListener(new ChangeListener() {
			public void changed(ChangeEvent event, Actor actor) {
				final StringBuilder buffer = new StringBuilder();
				final StringBuilder bufferSend = new StringBuilder();

				ScrollPane scrollPane = infoController.findActor("edit");
				WidgetGroup group = (WidgetGroup) scrollPane.getWidget();
				if (group.getChildren().size > 0) {
					SnapshotArray<Actor> array = group.getChildren();
					for (Actor actor2 : array) {
						Table table = (Table) actor2;
						String flag = (String) table.getUserObject();
						switch (flag) {
						case "card":
							TextField label = table.findActor("1");
							if (label != null && label.getText().length() > 0) {
								buffer.append("(卡牌ID:");
								buffer.append(label.getText());
								// send
								if (bufferSend.length() > 0) {
									bufferSend.append(",");
								}
								bufferSend.append("CARD-");
								bufferSend.append(label.getText());
								label = table.findActor("2");
								if (label != null
										&& label.getText().length() <= 0) {
									label.setText("1");
								}
								buffer.append("*");
								buffer.append(label.getText());
								buffer.append(")");

								// send
								bufferSend.append("*");
								bufferSend.append(label.getText());

							}
							break;
						case "item":
							label = table.findActor("1");
							if (label != null && label.getText().length() > 0) {
								buffer.append("(物品ID:");
								buffer.append(label.getText());
								// send
								if (bufferSend.length() > 0) {
									bufferSend.append(",");
								}
								bufferSend.append("ITEM-");
								bufferSend.append(label.getText());

								label = table.findActor("2");
								if (label != null
										&& label.getText().length() <= 0) {
									label.setText("1");
								}
								buffer.append("*");
								buffer.append(label.getText());
								buffer.append(")");

								// send
								bufferSend.append("*");
								bufferSend.append(label.getText());
							}
							break;
						case "money":
							label = table.findActor("2");
							if (label != null && label.getText().length() > 0) {
								buffer.append("(游戏币:");
								buffer.append("*");
								buffer.append(label.getText());
								buffer.append(")");

								// send
								if (bufferSend.length() > 0) {
									bufferSend.append(",");
								}
								bufferSend.append("M");
								bufferSend.append("*");
								bufferSend.append(label.getText());
							}
							break;
						case "stone":
							label = table.findActor("2");
							if (label != null && label.getText().length() > 0) {
								buffer.append("(代币:");
								buffer.append("*");
								buffer.append(label.getText());
								buffer.append(")");
								// send
								if (bufferSend.length() > 0) {
									bufferSend.append(",");
								}
								bufferSend.append("S");
								bufferSend.append("*");
								bufferSend.append(label.getText());
							}
							break;
						case "repute":
							label = table.findActor("2");
							if (label != null && label.getText().length() > 0) {
								buffer.append("(声望:");
								buffer.append("*");
								buffer.append(label.getText());
								buffer.append(")");
								// send
								if (bufferSend.length() > 0) {
									bufferSend.append(",");
								}
								bufferSend.append("R");
								bufferSend.append("*");
								bufferSend.append(label.getText());
							}
							break;
						}
					}
				}

				Table table = infoController.findActor("over");
				TextField label = table.findActor("id");
				final String id = label.getText().toString();
				if (id.length() <= 0) {
					new Dialog("提示", skin, "dialog") {
					}.text("请输入批次ID", labelStyle).button("Yes", true)
							.key(Keys.ENTER, true).key(Keys.ESCAPE, false)
							.show(menuController.getStage());
					return;
				}
				label = table.findActor("day");
				final String day = label.getText().toString();
				if (day.length() <= 0) {
					new Dialog("提示", skin, "dialog") {
					}.text("请输入失效时间", labelStyle).button("Yes", true)
							.key(Keys.ENTER, true).key(Keys.ESCAPE, false)
							.show(menuController.getStage());
					return;
				}
				label = table.findActor("num");
				final String num = label.getText().toString();
				if (num.length() <= 0) {
					new Dialog("提示", skin, "dialog") {
					}.text("请输入生成数量", labelStyle).button("Yes", true)
							.key(Keys.ENTER, true).key(Keys.ESCAPE, false)
							.show(menuController.getStage());
					return;
				}
				if (bufferSend.length() > 0) {
					new Dialog("提示", skin, "dialog") {
						protected void result(Object object) {
							System.out.println("Chosen: " + object);
							if (object.toString().equals("true")) {
								HTTP.send(
										new ByteArray().Allocate(20000)
												.PutUTF(bufferSend.toString())
												.PutInt(Integer.valueOf(id))
												.PutInt(Integer.valueOf(day))
												.PutInt(Integer.valueOf(num)),
										new NetCallback() {
											@Override
											public void callback(
													GameStatus status)
													throws IOException {
												// TODO Auto-generated method
												// stub
												if (status.isSuccess()) {
													DataInputStream _dis = (DataInputStream) status
															.getBindingObject();

													final StringBuilder builder = new StringBuilder(
															_dis.readUTF());
													byte b = _dis.readByte();
													if (b == 0) {
														ByteArrayOutputStream output = new ByteArrayOutputStream();
														byte[] buffer = new byte[2048];
														int n = 0;
														while (-1 != (n = _dis
																.read(buffer))) {
															output.write(
																	buffer, 0,
																	n);
														}
														output.flush();
														FileHandle handle = null;
														String path = "/codedata/code_"
																+ id + ".xls";
														if (Gdx.app.getType() == ApplicationType.Desktop) {
															handle = Gdx.files.absolute(System
																	.getProperty("user.dir")
																	+ path);
														} else {
															handle = Gdx.files
																	.external(path);
														}

														if (handle
																.isDirectory()) {
															handle.child("codedata");
														}

														handle.writeBytes(
																output.toByteArray(),
																false);
														builder.append("\n");
														builder.append("目录:"
																+ handle.file()
																		.getAbsolutePath());
													}
													Gdx.app.postRunnable(new Runnable() {
														@Override
														public void run() {
															new Dialog("提示",
																	skin,
																	"dialog") {
																protected void result(
																		Object object) {
																}
															}.text(builder
																	.toString(),
																	labelStyle)
																	.button("Yes",
																			true)
																	.key(Keys.ENTER,
																			true)
																	.key(Keys.ESCAPE,
																			false)
																	.show(menuController
																			.getStage());
														}
													});
												} else {
													Logger.error(this,
															status.getMessage());
												}
											}
										});

							}
						}
					}.text("是否确认当前编辑并提交至服务器生成相关礼包激活码？\n" + buffer + "\n"
							+ bufferSend, labelStyle).button("Yes", true)
							.button("No", false).key(Keys.ENTER, true)
							.key(Keys.ESCAPE, false)
							.show(menuController.getStage());
				} else {
					new Dialog("提示", skin, "dialog") {
						protected void result(Object object) {
						}
					}.text("请先编辑您要生成的内容", labelStyle).button("Yes", true)
							.key(Keys.ENTER, true).key(Keys.ESCAPE, false)
							.show(menuController.getStage());
				}
			}
		});
	}

	public Table getTable(String title, float x, float y, String tag,
			String message, String numMessage) {
		final Table table = new Table(skin);
		table.setPosition(x, y);
		table.setUserObject(tag);
		final LabelStyle labelStyle = new LabelStyle();
		labelStyle.font = bitmapFont;
		Label label = new Label(title, labelStyle);
		label.setColor(Color.GREEN);
		table.add(label);
		table.row();
		TextFieldStyle fieldStyle = skin.get(TextFieldStyle.class);
		fieldStyle.font = bitmapFont;
		fieldStyle.messageFont = bitmapFont;

		TextField textfield = new TextField("", fieldStyle);
		if (message != null) {
			textfield.setMessageText(message);
			textfield.setAlignment(Align.center);
			textfield.setName("1");
			table.add(textfield);
			textfield = new TextField("", fieldStyle);
		}
		textfield.setMessageText(numMessage);
		textfield.setAlignment(Align.center);
		textfield.setName("2");
		table.add(textfield);
		TextButtonStyle style = new TextButtonStyle(
				skin.get(TextButtonStyle.class));
		style.font = bitmapFont;
		TextButton iconButton = new TextButton("移除本项", style);
		iconButton.setWidth(120);
		iconButton.setHeight(30);
		infoController.addActor(iconButton);
		iconButton.addListener(new ChangeListener() {
			public void changed(ChangeEvent event, Actor actor) {
				table.getParent().removeActor(table);
			}
		});
		table.add(iconButton);
		return table;
	}

	public void initMenuController() {
		menuController = new WidgetGroup();
		menuController.setBounds(0, 0, 150, this.getHeight() - 1);
		menuController.setDebug(true);
		Texture texture = new Texture("Resources/image/navbg.jpg");
		Image image1 = new Image(texture);
		image1.setRotation(90);
		image1.setPosition(150, 0);
		menuController.addActor(image1);
		controller.addActor(menuController);

		TextButtonStyle style = new TextButtonStyle(
				skin.get(TextButtonStyle.class));
		style.font = bitmapFont;

		final LabelStyle labelStyle = skin.get(LabelStyle.class);
		labelStyle.font = bitmapFont;
		final WindowStyle windowStyle = skin.get("dialog", WindowStyle.class);
		windowStyle.titleFont = bitmapFont;
		int y = (int) (this.getHeight() - 50);

		Button iconButton = new TextButton("激活码", style);
		iconButton.setBounds(15, y, 120, 30);
		menuController.addActor(iconButton);
		y -= 50;
		iconButton = new TextButton("查看使用", style);
		iconButton.setBounds(15, y, 120, 30);
		menuController.addActor(iconButton);
		iconButton.addListener(new ChangeListener() {
			public void changed(ChangeEvent event, Actor actor) {
				new Dialog("提示", skin, "dialog") {
				}.text("该功能未实现.", labelStyle).button("Yes", true)
						.button("No", false).key(Keys.ENTER, true)
						.key(Keys.ESCAPE, false)
						.show(menuController.getStage());
			}
		});
		y -= 50;
		iconButton = new TextButton("关于", style);
		iconButton.setBounds(15, y, 120, 30);
		menuController.addActor(iconButton);
		iconButton.addListener(new ChangeListener() {
			public void changed(ChangeEvent event, Actor actor) {
				new Dialog("提示", skin, "dialog") {
					protected void result(Object object) {
						System.out.println("Chosen: " + object);
					}
				}.text("这是一个简易工具,如有UI建议,请于设计图发至邮箱:soells@foxmail.com.",
						labelStyle).button("Yes", true).button("No", false)
						.key(Keys.ENTER, true).key(Keys.ESCAPE, false)
						.show(controller.getStage());
			}
		});
	}

	public void menuControllerAction() {
		if (!menuAction) {
			Action complexAction = sequence(parallel(rotateBy(180, 2),
					scaleTo(1.4f, 1.4f, 2), alpha(0.7f, 2)));
			menuController.addAction(complexAction);
			menuAction = true;
		} else {
			Action complexAction = sequence(parallel(rotateBy(180, 1),
					scaleTo(1.0f, 1.0f, 2), alpha(1.0f, 2)));
			menuController.addAction(complexAction);
			menuAction = false;
		}
	}

	@Override
	public void free() {
		// TODO Auto-generated method stub

	}

	@Override
	public void callback(GameStatus status) throws IOException {
		// TODO Auto-generated method stub
		Logger.error(this, "回调指令=" + status.getStatusCode());
		switch (status.getStatusCode()) {
		case 10000:
			// TODO Auto-generated method stub
			if (status.isSuccess()) {
				DataInputStream _dis = (DataInputStream) status
						.getBindingObject();
				int size = _dis.readUnsignedShort();
				final Array<String> array = new Array<String>();

				for (int i = 0; i < size; i++) {
					String msg = _dis.readUTF();
					array.add(msg);
				}

				Gdx.app.postRunnable(new Runnable() {
					@Override
					public void run() {
						List<String> list = new List<String>(skin);
						list.setItems(array);
						list.getSelection().setMultiple(true);
						list.getSelection().setRequired(false);
						ScrollPane scrollPane = ((Group) infoController
								.findActor("get")).findActor("dataScroll");
						scrollPane.setWidget(list);
					}
				});

			} else {
				Logger.error(this, status.getMessage());
			}

			break;

		default:
			break;
		}
	}

}
